using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Lzfy_Refund_Service.Services;
using Lzfy_Refund_Service.Models;

namespace Lzfy_Refund_Service.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class VerifyInfoController : ControllerBase
    {
        private readonly IVerifyInfoService _verifyInfoService;
        private readonly ILogger<VerifyInfoController> _logger;

        public VerifyInfoController(IVerifyInfoService verifyInfoService, ILogger<VerifyInfoController> logger)
        {
            _verifyInfoService = verifyInfoService;
            _logger = logger;
        }

        /// <summary>
        /// 根据ID获取验证码信息
        /// </summary>
        /// <param name="id">验证码信息ID</param>
        /// <returns>验证码信息</returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<VerifyInfo>> GetById(int id)
        {
            try
            {
                var verifyInfo = await _verifyInfoService.GetByIdAsync(id);
                if (verifyInfo == null)
                {
                    return NotFound($"Verify info with ID {id} not found");
                }
                return Ok(verifyInfo);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting verify info by ID {Id}", id);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 获取所有验证码信息
        /// </summary>
        /// <returns>验证码信息列表</returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<VerifyInfo>>> GetAll()
        {
            try
            {
                var verifyInfos = await _verifyInfoService.GetAllAsync();
                return Ok(verifyInfos);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting all verify infos");
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 根据患者ID获取验证码信息
        /// </summary>
        /// <param name="patientId">患者ID</param>
        /// <returns>验证码信息列表</returns>
        [HttpGet("patient/{patientId}")]
        public async Task<ActionResult<IEnumerable<VerifyInfo>>> GetByPatientId(string patientId)
        {
            try
            {
                var verifyInfos = await _verifyInfoService.GetByPatientIdAsync(patientId);
                return Ok(verifyInfos);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting verify infos by patient ID {PatientId}", patientId);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 根据验证码获取验证码信息
        /// </summary>
        /// <param name="verifyCode">验证码</param>
        /// <returns>验证码信息</returns>
        [HttpGet("verify-code/{verifyCode}")]
        public async Task<ActionResult<VerifyInfo>> GetByVerifyCode(string verifyCode)
        {
            try
            {
                var verifyInfo = await _verifyInfoService.GetByVerifyCodeAsync(verifyCode);
                if (verifyInfo == null)
                {
                    return NotFound($"Verify info with verify code '{verifyCode}' not found");
                }
                return Ok(verifyInfo);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting verify info by verify code {VerifyCode}", verifyCode);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 根据二维码获取验证码信息
        /// </summary>
        /// <param name="qrCode">二维码</param>
        /// <returns>验证码信息</returns>
        [HttpGet("qr-code/{qrCode}")]
        public async Task<ActionResult<VerifyInfo>> GetByQrCode(string qrCode)
        {
            try
            {
                var verifyInfo = await _verifyInfoService.GetByQrCodeAsync(qrCode);
                if (verifyInfo == null)
                {
                    return NotFound($"Verify info with QR code '{qrCode}' not found");
                }
                return Ok(verifyInfo);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting verify info by QR code {QrCode}", qrCode);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 获取最近10分钟的验证码信息
        /// </summary>
        /// <param name="userId">用户ID（可选）</param>
        /// <returns>最近10分钟的验证码信息列表</returns>
        [HttpGet("recent")]
        public async Task<ActionResult<object>> GetRecentVerifyInfos([FromQuery] string? userId = null)
        {
            try
            {
                var verifyInfos = await _verifyInfoService.GetRecentAsync(10, userId);
                return Ok(new { success = true, data = verifyInfos, message = "获取成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting recent verify infos");
                return Ok(new { success = false, data = (object?)null, message = "获取失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 根据条件查询验证码信息（分页）
        /// </summary>
        /// <param name="request">查询条件</param>
        /// <returns>分页的验证码信息</returns>
        [HttpPost("search")]
        public async Task<ActionResult<VerifyInfoQueryResponse>> Search([FromBody] VerifyInfoQueryRequest request)
        {
            try
            {
                var response = await _verifyInfoService.GetWithFilterAsync(request);
                return Ok(response);
            }
            catch (ArgumentNullException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error searching verify infos");
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 创建新的验证码信息
        /// </summary>
        /// <param name="request">创建请求</param>
        /// <returns>创建的验证码信息ID</returns>
        [HttpPost]
        public async Task<ActionResult<int>> Create([FromBody] VerifyInfoCreateRequest request)
        {
            try
            {
                var id = await _verifyInfoService.CreateAsync(request);
                return CreatedAtAction(nameof(GetById), new { id }, id);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (InvalidOperationException ex)
            {
                return Conflict(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating verify info");
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 更新验证码信息
        /// </summary>
        /// <param name="id">验证码信息ID</param>
        /// <param name="request">更新请求</param>
        /// <returns>更新结果</returns>
        [HttpPut("{id}")]
        public async Task<ActionResult> Update(int id, [FromBody] VerifyInfoUpdateRequest request)
        {
            try
            {
                var success = await _verifyInfoService.UpdateAsync(id, request);
                if (!success)
                {
                    return NotFound($"Verify info with ID {id} not found");
                }
                return NoContent();
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (InvalidOperationException ex)
            {
                return Conflict(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating verify info with ID {Id}", id);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 删除验证码信息
        /// </summary>
        /// <param name="id">验证码信息ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult> Delete(int id)
        {
            try
            {
                var success = await _verifyInfoService.DeleteAsync(id);
                if (!success)
                {
                    return NotFound($"Verify info with ID {id} not found");
                }
                return NoContent();
            }
            catch (InvalidOperationException ex)
            {
                return NotFound(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting verify info with ID {Id}", id);
                return StatusCode(500, "Internal server error");
            }
        }
        
        /// <summary>
        /// 软删除验证码信息
        /// </summary>
        /// <param name="id">验证码信息ID</param>
        /// <param name="deletedBy">删除操作者</param>
        /// <returns>删除结果</returns>
        [HttpPatch("{id}/soft-delete")]
        public async Task<ActionResult> SoftDelete(int id, [FromBody] string? deletedBy)
        {
            try
            {
                if (string.IsNullOrEmpty(deletedBy))
                {
                    return BadRequest("删除操作者不能为空");
                }
                
                var success = await _verifyInfoService.SoftDeleteAsync(id, deletedBy);
                if (!success)
                {
                    return NotFound($"Verify info with ID {id} not found");
                }
                return NoContent();
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error soft deleting verify info with ID {Id}", id);
                return StatusCode(500, "Internal server error");
            }
        }
    }
}